/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "cmcertcommon_fuzzer.h"

#include <cstring>

#include "cert_manager.h"
#include "cert_manager_api.h"
#include "cert_manager_app_cert_process.h"
#include "cm_event_process.h"
#include "cm_fuzz_test_common.h"
#include "cm_test_common.h"
#include "cm_cert_data_ecc.h"
#include "cm_cert_data_part1_rsa.h"
#include "cm_x509.h"
#include "cm_ipc_client_serialization.h"

#define MAX_OUT_BLOB_SIZE (5 * 1024 * 1024)
#define INVALID_VALUE 0XFFFFFFFF

namespace {
    const struct CmBlob g_eccAppCert = { sizeof(g_eccP256P12CertInfo), const_cast<uint8_t *>(g_eccP256P12CertInfo) };
    const struct CmBlob g_appCertPwd = { sizeof(g_certPwd), const_cast<uint8_t *>(g_certPwd) };
    const uint32_t  UINT32_COUNT = 4;
    const uint32_t  CM_BLOB_COUNT = 2;
}

using namespace CmFuzzTest;

namespace OHOS {
    struct MultipleParams {
        uint32_t value;
        uint32_t srcOffset;
        struct CmBlob blob;
        struct CmBlob outData;
    };

    struct BufferContext {
        uint8_t* myData;
        uint32_t* remainSize;
        uint32_t* offset;
    };

    class BufferParamReader {
    public:
        static bool ReadMultipleParams(BufferContext& ctx, MultipleParams& params)
        {
            if (!GetUintFromBuffer(ctx.myData, ctx.remainSize, ctx.offset, &params.value)) {
                return false;
            }

            if (!GetUintFromBuffer(ctx.myData, ctx.remainSize, ctx.offset, &params.srcOffset)) {
                return false;
            }

            if (!GetCmBlobFromBuffer(ctx.myData, ctx.remainSize, ctx.offset, &params.blob)) {
                return false;
            }

            if (!GetCmBlobFromBuffer(ctx.myData, ctx.remainSize, ctx.offset, &params.outData)) {
                return false;
            }

            return true;
        }
    };

    class CertificateProcessor {
    public:
        static void ProcessCertificateUnpack(MultipleParams& params, struct CmBlob* keyUri)
        {
            struct CertAbstract abstract = { {0}, {0}, false, {0} };
            struct CertList certificateList = { 1, &abstract };
            struct CertInfo cInfo;
            (void)memset_s(&cInfo, sizeof(CertInfo), 0, sizeof(CertInfo));
            (void)GetUint32FromBuffer(&params.value, keyUri, &params.srcOffset);
            (void)CmGetBlobFromBuffer(&params.blob, keyUri, &params.srcOffset);
            (void)CmCertificateListUnpackFromService(&params.outData, &certificateList);
            (void)CmCertificateInfoUnpackFromService(&params.outData, keyUri, &cInfo);
        }
    };

    bool DoSomethingInterestingWithMyAPIIpc(const uint8_t* data, size_t size)
    {
        uint32_t minSize = sizeof(struct CmBlob) * CM_BLOB_COUNT +sizeof(uint32_t) * UINT32_COUNT;
        uint8_t *myData = nullptr;
        if (!CopyMyData(data, size, minSize, &myData)) {
            return false;
        }

        uint32_t remainSize = static_cast<uint32_t>(size);
        uint32_t offset = 0;
        char retUriBuf[MAX_OUT_BLOB_SIZE] = {0};
        struct CmBlob keyUri = {sizeof(retUriBuf), reinterpret_cast<uint8_t *>(retUriBuf) };
        uint8_t certAliasBuf[] = "PrivKeyA";
        struct CmBlob certAlias = { sizeof(certAliasBuf), certAliasBuf };
        struct CmBlob privKey = { 0, NULL };
        struct CmAppCertParam appCertParam = { (struct CmBlob *)&g_eccAppCert, (struct CmBlob *)&g_appCertPwd,
            &certAlias, CM_CREDENTIAL_STORE, INIT_INVALID_VALUE, CM_AUTH_STORAGE_LEVEL_EL2,
            FILE_P12, &privKey, DEFAULT_FORMAT };
        if (CertManagerInitialize() != 0) {
            CmFree(myData);
            return false;
        }

        uint32_t uid = 20020156;
        uint32_t userId = 100;
        CmContext cmContext;
        cmContext.uid = uid;
        cmContext.userId = userId;
        CmInstallAppCertPro(&cmContext, &appCertParam, &keyUri);
        struct CmAppUidList appUidList = { MAX_OUT_BLOB_SIZE + 1, nullptr };
        if (!CmGetAuthorizedAppList(&keyUri, &appUidList)) {
            return false;
        }
        
        BufferContext bufferCtx = {myData, &remainSize, &offset};
        MultipleParams params;
        if (!BufferParamReader::ReadMultipleParams(bufferCtx, params)) {
            CmFree(myData);
            CmFree(appUidList.appUid);
            return false;
        }

        CertmanagerTest::MockHapToken mockHap;
        CertificateProcessor::ProcessCertificateUnpack(params, &keyUri);
        (void)CmUninstallAppCert(&keyUri, CM_CREDENTIAL_STORE);
        CmFree(myData);
        CmFree(appUidList.appUid);
        return true;
    }

    bool DoSomethingInterestingWithMyAPICmEventProcess(const uint8_t* data, size_t size)
    {
        char retUriBuf[MAX_OUT_BLOB_SIZE] = {0};
        struct CmBlob keyUri = {sizeof(retUriBuf), reinterpret_cast<uint8_t *>(retUriBuf) };
        uint8_t certAliasBuf[] = "PrivKeyA";
        struct CmBlob certAlias = { sizeof(certAliasBuf), certAliasBuf };
        struct CmBlob privKey = { 0, NULL };
        struct CmAppCertParam appCertParam = { (struct CmBlob *)&g_eccAppCert, (struct CmBlob *)&g_appCertPwd,
            &certAlias, CM_CREDENTIAL_STORE, INIT_INVALID_VALUE, CM_AUTH_STORAGE_LEVEL_EL2,
            FILE_P12, &privKey, DEFAULT_FORMAT };
        uint32_t uid = 20020156;
        uint32_t userId = 100;
        CmContext cmContext;
        cmContext.uid = uid;
        cmContext.userId = userId;
        if (CertManagerInitialize() != 0) {
            return false;
        }

        CmContext cmContext1;
        cmContext1.uid = INVALID_VALUE;
        cmContext1.userId = userId;
        CmInstallAppCertPro(&cmContext, &appCertParam, &keyUri);
        CertmanagerTest::MockHapToken mockHap;
        (void)CmDeleteProcessInfo(&cmContext);
        (void)CmDeleteProcessInfo(&cmContext1);
        (void)CmUninstallAppCert(&keyUri, CM_CREDENTIAL_STORE);
        return true;
    }
}

/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
    /* Run your code on data */
    OHOS::DoSomethingInterestingWithMyAPIIpc(data, size);
    OHOS::DoSomethingInterestingWithMyAPICmEventProcess(data, size);
    return 0;
}